package com.wxb.quartz.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Feng Yu
 * @version V1.0
 * @date 2017-05-26
 */
public class GenericResCtx {
    private final static Logger logger = LoggerFactory.getLogger(GenericResCtx.class);

    private JSONObject resObj;
    private JSONObject rtnObj;

    public GenericResCtx(){}

    public GenericResCtx(String result){
        try{
            resObj = JSONObject.parseObject(result);
            if(resObj != null){
                this.rtnObj = resObj.getJSONObject("rtnObj");
            }
        }catch (Exception e){
            logger.error("JSON.parse.error. > " + e);
        }
    }

    public boolean isSuccess(){
        if(GenericCode.success_code.equals(this.getRtnCode())){
            return true;
        }
        return false;
    }

    public String getRtnCode() {
        if(resObj != null){
            return resObj.getString("rtnCode");
        }
        return GenericCode.error_rtnCode_nonExistent;
    }

    public String getRtnMsg() {
        if(resObj != null){
            return resObj.getString("rtnMsg");
        }
        return "rtnMsg non-existent";
    }

    public JSONObject getRtnObj() {
        return rtnObj;
    }

    public int getTotal() {
        if(rtnObj != null){
            return rtnObj.getIntValue("total");
        }
        return 0;
    }

    public JSONArray getList() {
        if(rtnObj != null){
            return rtnObj.getJSONArray("list");
        }
        return null;
    }

    public Object[] getRtn2Array(){
        if(rtnObj != null &&rtnObj.containsKey("list")){
            return rtnObj.getJSONArray("list").toArray();
        }
        return null;
    }

    public Object getRtn2Bean(Class clazz){
        if(resObj != null && clazz != null && resObj.containsKey("rtnObj")){
            return resObj.getObject("rtnObj", clazz);
        }
        return null;
    }

    public List getRtn2BeanList(Class clazz){
        if(rtnObj != null && clazz != null && rtnObj.containsKey("list")){
            return rtnObj.getJSONArray("list").toJavaList(clazz);
        }
        return null;
    }

    public static void main(String[] args){
        String str ="{\"rtnCode\":\"0000\", \"rtnObj\":{\"total\":\"5\", \"list\":[{\"id\":\"22\"},{\"id\":\"33\"}]}}";
        GenericResCtx ctx = new GenericResCtx(str);
        System.out.println(ctx.getTotal());
        System.out.println(ctx.getRtnObj());
        System.out.println(ctx.getRtn2Array().length);
    }
}
